package com.qf.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.dao.UserMapper;
import com.qf.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 千锋健哥
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //1. 判断用户名不为空, 如果为空返回错误信息
        if (userName == null || "".equals(userName)) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        //2. 根据用户名到数据库中获取用户对象
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", userName);
        Users users = userMapper.selectOne(queryWrapper);

        //3. 判断如果用户对象为空, 说明用户名错误, 返回错误信息
        if(users == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        //4. 根据用户id, 查询对应的角色列表
        List<String> roleList = userMapper.findRoleListByUserId(users.getId());

        //5. 根据用户id, 查询对应的权限列表
        List<String> menuList = userMapper.findMenuListByUserId(users.getId());

        //6. 封装权限集合
        List<GrantedAuthority> authList = new ArrayList<>();

        //7. 将角色列表封装到权限集合中
        if (roleList != null) {
            for (String roleStr : roleList) {
                authList.add(new SimpleGrantedAuthority(roleStr));
            }
        }

        //8. 将权限列表封装到权限集合中
        if (menuList != null) {
            for (String menuStr : menuList) {
                authList.add(new SimpleGrantedAuthority(menuStr));
            }
        }

        //4. 将用户名, 密码, 权限集合封装成UserDetails对象返回给SpringSecurity框架
        User user = new User(userName, users.getPassword(), authList);
        return user;
    }

}
